import moment from 'moment';
import schedule from 'node-schedule'
import { REDIS_KEY } from '../declare/keys';
import { LiverBaseInfo } from '../declare/liver';
import { getRedisClient } from '../library/redis';
import { insertMany, findOne } from '../service/mongoUtil';

const redis = getRedisClient()


export function scheduleSaveRank(){
  const job = schedule.scheduleJob('0 0 */1 * * *', async (fireDate) => {
    console.log("job start")
    await saveWaterData(fireDate)
  });
}

async function saveWaterData(fireDate: Date) {
  console.log('savingdata');
  const dataSet = await redis.zrevrange(REDIS_KEY.REDIS_KEY_GIFT_RANK, 0, -1, 'WITHSCORES')
  //console.log(dataSet)
  const dataWater: { timestamp: number, date: string, authorId: number, name: string, rank: number, value: number }[] = []
  let rank = 1;
  for (let index = 0; index < dataSet.length; index += 2) {
    const authorId = Number(dataSet[index])
    const score = Number(dataSet[index + 1])
    console.log(authorId, score)
    const liverInfo: LiverBaseInfo = await findOne("t_liver_base_info", { id: authorId })
    dataWater.push({ date:moment(fireDate).format('YYYY-MM-DD HH'),timestamp: fireDate.getTime(), authorId, value: score, rank, name: liverInfo.name })
    rank += 1
  }
  //console.log(dataWater)
  await insertMany(dataWater, "t_rank_snapshot")
};

//saveWaterData(new Date())